﻿package fwk.siteManager {	


	import flash.events.EventDispatcher;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode
	import flash.display.StageQuality;
	import fwk.siteManager.BO.PageData;
	import fwk.siteManager.BO.RessourceData;
	import fwk.siteManager.BO.TemplateData;
	import fwk.loaderManager.events.LoaderEvent;
	import fwk.siteManager.managers.DataManager;
	
	import fwk.panelLoading.LoadingDisplayer;
	import fwk.loaderManager.*;
	import fwk.loaderManager.events.*;
	import fwk.siteManager.events.ContainerLoaderEvent;
	import fwk.com.asual.swfaddress.*;
	import fwk.com.hexagonstar.util.debug.Debug;
	
	import flash.display.MovieClip;
	import flash.display.DisplayObject;
	import flash.events.Event;
	import flash.display.LoaderInfo;
	import flash.utils.getDefinitionByName;
	import flash.system.Capabilities;
	
	import fwk.siteManager.managers.RessourcesManager;
	
	public class ContainerLoader extends MovieClip
	{
		
		///////////////////////////
		// private properties
		private static var  _instance:ContainerLoader;
		private static var _increment:int = 0;
		
		private var _loaderPanel:LoadingDisplayer;
		protected var _loaderPanelSite:LoadingDisplayer;
		protected var _loaderPanelPage:LoadingDisplayer;
		private var _loaderManager:LoaderManager;
		

		private var _ressourcesManager:RessourcesManager;
		private var _dataManager:DataManager;
		
		
		protected var _urlXmlConfig:String;
		private var _xmlConfig:XML;
		private var _xmlTemplates:XML;
		private var _xmlContentPage:XML;
		private var _loaderItemXmlContent:LoaderItemObject;
		
		private var _repLoc:String;		// repertoire de localisation
		private var _repShared:String;		// repertoire shared
			
		private var _idCurrentPage:String;
		private var _deepLinkToLoad:String;
		private var _deepLinkFirst:String;
		private var _onLoadingPage:Boolean;
		
		private var _flashVarNavigationName:String ;
		private var _flashVarSharedPathName:String ;
		private var _flashVarLocaPathName:String ;
		
		private var _debugMode:Boolean;
		
		//For SWF Address
		private var _isSwfAdd:Boolean;
		private var _splitDeepLink:String;
		private var _listAd:XMLList;
		
		
	

		
		//----------------------------------------------------------------------
		// récup ressources
		//----------------------------------------------------------------------
		// renvoi la ressource correspondant au nom passé en paramètre
		public function getloaderItemRessourceGlobal(id:String):LoaderItemObject
		{
			return _ressourcesManager.getRessourceGlobal(id);
			
		}

		public function getloaderItemStructure(id:String):LoaderItemObject
		{
			return _ressourcesManager.getRessourceClipStructure(id);

		}
		public function getLoaderItemPage(id:String):LoaderItemGroup
		{
			
			return _ressourcesManager.getRessourcePage(id) as LoaderItemGroup;

		}
		public function getLoaderItemRessource(id:String):LoaderItemGroup
		{
			
			return _ressourcesManager.getRessourceGroup(id) as LoaderItemGroup;

		}
		public function getLoaderItemTemplate(id:String):LoaderItemGroup
		{

			return _ressourcesManager.getRessourceTemplate(id) as LoaderItemGroup;
			
			
		}

		/*public function get loaderPanel():LoadingDisplayer{
			return _loaderPanel;
		}*/
		public function get xmlContentPage():XML{
			return _xmlContentPage;
		}
		public function get xmlTemplates():XML{
			return _xmlTemplates;
		}
		public function get xmlConfig():XML{
			return _xmlConfig;
		}
		public function get localPath():String{
			return _repLoc;
		}
		public function get sharedPath():String{
			return _repShared;
		}
		public static function getInstance():ContainerLoader
		{
			
			if ( _instance == null)
			{
				_instance = new ContainerLoader();
			}
			
			return _instance;
		}
		public function get loaderManager():LoaderManager
		{
			return _loaderManager;
		}
		public function get splitDeepLink():String{
			return _splitDeepLink;
		}
		public function get deepLinkToLoad():String{
			return _deepLinkToLoad;
		}
		public function get swfAddActif():Boolean{
			return _isSwfAdd;
		}
		
		public function get dataManager():DataManager { return _dataManager; }
		
		public function get ressourcesManager():RessourcesManager { return _ressourcesManager; }
		

		public function get debugMode():Boolean { return _debugMode; }
		
		public function set debugMode(value:Boolean):void 
		{
			_debugMode = value;
		}
		
		public function set splitDeepLink(value:String):void 
		{
			_splitDeepLink = value;
		}
		
		public function set isSwfAdd(value:Boolean):void 
		{
			_isSwfAdd = value;
		}
		

		
		
		
		//-----------------------------------------------------------------------
		// Constructeur
		//-----------------------------------------------------------------------
		function ContainerLoader()
		{

			if (stage != null) {
				
				
				//alignement
				// stage setup for resizing
				stage.scaleMode						= StageScaleMode.NO_SCALE;
				stage.align							= StageAlign.TOP_LEFT;
				//stage.quality						= StageQuality.HIGH;
				stage.showDefaultContextMenu		= false;
				stage.stageFocusRect				= false;
				

				
				if (_increment == 0) {
					
					
					if( _urlXmlConfig == null) _urlXmlConfig 					= "shared/xml/config.xml";
					_repLoc 						= "";
					_repShared 						= "";
					_flashVarNavigationName 		= "page";
					_flashVarSharedPathName 		= "sharedPath";
					_flashVarLocaPathName 			= "countryPath";
					if( _debugMode != true) _debugMode 						= false;
					
					//For SWF Address
					if( _isSwfAdd != true) _isSwfAdd 						= false;
					if( _splitDeepLink == null) _splitDeepLink 				= "/";

					_onLoadingPage 											= false;

					//recup flashVars
						if(LoaderInfo(loaderInfo).parameters.config != null)
						_urlXmlConfig = LoaderInfo(loaderInfo).parameters.config;
						
					//recup flashVars date
						var datecache:String = "";
						if(LoaderInfo(loaderInfo).parameters.datecache != null)
						datecache = LoaderInfo(loaderInfo).parameters.datecache;
						
					//recup flashVars noCache
					var noCache:String = "false";
					if(LoaderInfo(loaderInfo).parameters.noCache != null)
					noCache = LoaderInfo(loaderInfo).parameters.noCache;
					
					
					// on instancie le gestionnaie de chargement des ressources
					_loaderManager = new LoaderManager();
					if (datecache != "") _loaderManager.idLastCache = datecache; // date du cache à utilisé
					if (noCache == "true") _loaderManager.noCache = true;
					
					
					// init ressources manager
					_ressourcesManager = new RessourcesManager();
					_ressourcesManager.idLastCache = _loaderManager.idLastCache;
					_ressourcesManager.noCache = _loaderManager.noCache;
					
					// data manager
					_dataManager = new DataManager();
					
					
					// on instancie le loader panel du site
					var classPanLoad:Class = getDefinitionByName("mcLoader_001") as Class;
					_loaderPanelSite = new classPanLoad();
					
					// on instancie le loader panel des pages
					var classPanLoadPage:Class = getDefinitionByName("mcLoader_001") as Class;
					_loaderPanelPage = new classPanLoadPage();
					
					//swfAdress
					SWFAddress.addEventListener(SWFAddressEvent.INIT, onSwfAdressReady);
					
					_instance = this;
					_increment++;
					_deepLinkToLoad = "";
					_deepLinkFirst = "";
					

				}else
				{
					debugIt("Attention !!!! Vous devez utiliser la méthode getInstance() pour récupéré l'instance de la classe ContainerLoader");
				}
			}
			
		}
		//----------------------------------------------------------------------
		//-- Methods
		//----------------------------------------------------------------------
		private function onSwfAdressReady(evt:SWFAddressEvent)
		{
			debugIt("onSwfAdressReady");
			SWFAddress.removeEventListener(SWFAddressEvent.INIT, onSwfAdressReady);
			
			

			
			loadConfig();
		
		}
		//----------------------------------------------------------------------
		private function loadConfig()
		{
			
			// chargement du xml de config et xml des pages
				// on crée les objects ressource
				var item:LoaderItemObject = new LoaderItemObject("xmlConfig", _urlXmlConfig);
				_ressourcesManager.addToCacheStatic(item);
				
				_loaderManager.add(item);
				_loaderManager.addEventListener(LoaderEvent.COMPLETED, onConfigComplete);
				_loaderManager.start();
		
		}
		//----------------------------------------------------------------------
		public function onConfigComplete(evt:LoaderEvent):void
		{
				
			_loaderManager.removeEventListener(LoaderEvent.COMPLETED, onConfigComplete);
			
			
			// on récupère le xml
			_xmlConfig = new XML( (  _ressourcesManager.getRessource("xmlConfig") as LoaderItemObject).content as String);
			
			initDebug();
			
			//default Paths
			_repLoc = _xmlConfig.defaultPaths.@countryPath;
			_repShared = _xmlConfig.defaultPaths.@sharedPath;
			
			//flashVars paths
			if(LoaderInfo(loaderInfo).parameters[_flashVarLocaPathName] != null)
			_repLoc = LoaderInfo(loaderInfo).parameters[_flashVarLocaPathName];
				
			if(LoaderInfo(loaderInfo).parameters[_flashVarSharedPathName] != null)
			_repShared = LoaderInfo(loaderInfo).parameters[_flashVarSharedPathName];
			

			var rep:String;
			rep = _repShared;
			_loaderManager.reset();

			if(_xmlConfig.contentDisplayed.@url != ""){
			
				if (_xmlConfig.contentDisplayed.@path != null && _xmlConfig.contentDisplayed.@path == "countryPath") rep = _repLoc;
				if (_xmlConfig.contentDisplayed.@path != null && _xmlConfig.contentDisplayed.@path == "external") rep = "";
				
				var item:LoaderItemObject = new LoaderItemObject("xmlTemplates", rep+_xmlConfig.contentDisplayed.@url);			
				_loaderManager.add(item);
				_ressourcesManager.addToCacheStatic(item);
			}
			
			
			// swf address
			debugIt(" --> swfAddress actif ");
			SWFAddress.addEventListener(SWFAddressEvent.CHANGE, onSwfAdressChange);
			
			if(_xmlConfig.swfAddress[0] is XML && _xmlConfig.swfAddress.@url != ""){
				_isSwfAdd = true;
				
				rep = _repShared;
				if (_xmlConfig.swfAddress.@path != null && _xmlConfig.swfAddress.@path == "countryPath") rep = _repLoc;
				if (_xmlConfig.swfAddress.@path != null && _xmlConfig.swfAddress.@path == "external") rep = "";
					
				var item2:LoaderItemObject = new LoaderItemObject("xmlSwfAd", rep+_xmlConfig.swfAddress.@url);			
				_loaderManager.add(item2);
				_ressourcesManager.addToCacheStatic(item2);
			}
			
			
			
			_loaderManager.addEventListener(LoaderEvent.COMPLETED, onTemplatesXmlComplete);
			_loaderManager.start();
		}
		//----------------------------------------------------------------------
		private function onTemplatesXmlComplete(evt:LoaderEvent)
		{
			trace("onTemplatesXmlComplete");
			
			_loaderManager.removeEventListener(LoaderEvent.COMPLETED, onTemplatesXmlComplete);
			_loaderManager.reset();
			

			if(_isSwfAdd)
			{
				var listAd	= new XML(String(getloaderItemRessourceGlobal("xmlSwfAd").content));
					_listAd = listAd.addressPages;
			}
			
			
			onReady();
			
			
			if (_ressourcesManager.getRessource("xmlTemplates") != null  )
			{
				// on récupère le xml
				_xmlTemplates = new XML((_ressourcesManager.getRessource("xmlTemplates") as LoaderItemObject).content as String);

				defineFirstPage();
				
			}else {
				
				_xmlTemplates = _xmlConfig.contentDisplayed[0];
				
				startLoadRessources();
			}
			
			
			
		}
		//----------------------------------------------------------------------
		public function onReady():void
		{
			
			
		}
		//----------------------------------------------------------------------
		private function defineFirstPage()
		{
			debugIt("defineFirstPage");
			_flashVarNavigationName = _xmlConfig.flashvarNavigationName.@name;
		

			// on récupère l'id de la première page (LoaderItemGroup) à afficher du xml templates
			_deepLinkToLoad = _xmlTemplates.pages.@defaultPageDisplayed;
			
			// si existe on récupère l'id de la première page à charger depuis la flashvar
			if(LoaderInfo(loaderInfo).parameters[_flashVarNavigationName] != null)
			{
				debugIt("LoaderInfo(loaderInfo).parameters[_flashVarNavigationName] " + LoaderInfo(loaderInfo).parameters[_flashVarNavigationName]);
				_deepLinkToLoad = LoaderInfo(loaderInfo).parameters[_flashVarNavigationName];
			}
			
			var initialSwfAddress:String = SWFAddress.getValue();
			debugIt("initialSwfAddress " + initialSwfAddress);

			
			if (_deepLinkToLoad.substring(0, 1) != "/") {
				_deepLinkToLoad = "/" + _deepLinkToLoad;
			}

			
			if(initialSwfAddress != "" && initialSwfAddress != "/")
			{
				if(_isSwfAdd)
					_deepLinkToLoad = getDeepLinkFromSwfAdd(initialSwfAddress);
				else 
					_deepLinkToLoad = initialSwfAddress;
					
			}

			debugIt("_deepLinkToLoad " + _deepLinkToLoad);
			
			
			// on regarde si l'id page est id ou un xml
			if (_deepLinkToLoad.indexOf(".xml") != -1)
			{	
				var urlClean:String = _deepLinkToLoad;
				if ( _deepLinkToLoad.substring(0, 1) == "/") {
					urlClean = _deepLinkToLoad.substr(1, _deepLinkToLoad.length);
				}
				
				
				_loaderItemXmlContent = new LoaderItemObject("xmlContent", _repLoc + urlClean);
				addEventListener("__onXmlContentLoaded", startLoadRessources);
				

				
				_loaderManager.addEventListener(LoaderEvent.COMPLETED, onXmlContentCompleted);
				_loaderManager.reset();
				_loaderManager.add(_loaderItemXmlContent);
				_loaderManager.start();
				
				
			}else
			{
				startLoadRessources();
			}
			

			
		}
		//----------------------------------------------------------------------
		private function onXmlContentCompleted(evt:LoaderEvent)
		{	
			_loaderManager.removeEventListener(LoaderEvent.COMPLETED, onXmlContentCompleted);

			_xmlContentPage = new XML(_loaderItemXmlContent.content as String);
			
			if (_xmlContentPage.children()[0].@uiTemplate != undefined)
			{	
				dispatchEvent(new Event("__onXmlContentLoaded"));
			}else {
				
				trace("XXXX Error xml content, manque idTemplate ");
			}
			
			
		}
		
		// retire les indications de sous niveau de la chaine id page
		private function getIdPageClean(id:String):String {
			
			
			var idPage:String = id;
			var tab:Array = id.split(_splitDeepLink);
			if (tab != null && tab.length > 1) idPage = tab[1];
			
			
			return idPage;
		}

		//----------------------------------------------------------------------
		private function isInXmlContent(nameNode:String):Boolean
		{
			
			for (var j:int = 0; j < _xmlContentPage.children()[0].content.children().length(); j++)
			{
				if (nameNode == _xmlContentPage.children()[0].content.children()[j].name()) {
					return true;
				}
				
			}
			
			return false;
			
		}
		
		
		//----------------------------------------------------------------------
		private function startLoadRessources(evt:Event = null)
		{
			
			//tableau qui va contenir les ressources initiales à charger
			var tabRessourceInitial:Array = new Array();
			debugIt("");
			debugIt("------------------------------------- ");
			debugIt("startLoadRessources ");
			debugIt("------------------------------------- ");
			debugIt("idFirstPage " + _deepLinkToLoad);
			

			//------------------------------------------
			// recup des ressources global à charger
			//------------------------------------------
			// on récupère du xml config les ressources global à chargé qu'on range des dans object LoaderItemObject
			for (var i:int = 0; i < _xmlConfig.ressourcesGlobal.children().length(); i++)
			{
				var item:LoaderItemObject = _ressourcesManager.getRessourceGlobal( _xmlConfig.ressourcesGlobal.children()[i].@id );
				//_ressourcesManager.addToCacheStatic(item); par defaut en cache
				tabRessourceInitial.push(item);
			}
			
			
			//------------------------------------------
			// recup des clips de la structure du site à charger
			//------------------------------------------
			for (i = 0; i < _xmlTemplates.structure.clip.length(); i++)
			{
				
				var item2:LoaderItemObject = _ressourcesManager.getRessourceClipStructure(  _xmlTemplates.structure.clip[i].@id );
				//_ressourcesManager.addToCacheStatic(item2); par defaut en cache
				tabRessourceInitial.push(item2);
			}
			
			
			//------------------------------------------
			// première page à charger
			//------------------------------------------

			if (_deepLinkToLoad != null && _deepLinkToLoad != "")
			{
				_deepLinkFirst = _deepLinkToLoad;
				
				var itemPage:LoaderItemGroup;
				var itemTemplate:LoaderItemGroup;
				var uipage:String;
				
					
				if (_deepLinkToLoad.indexOf(".xml") != -1)
				{	
					_instance.removeEventListener("__onXmlContentLoaded", startLoadRessources);
					
					// si le xml chargé à une déclaration dans la liste des pages de templates.xml
					uipage = _deepLinkToLoad;
					
	
					itemPage = _ressourcesManager.getRessourcePage(uipage) as LoaderItemGroup;
					if (itemPage != null) {
						tabRessourceInitial.push(itemPage);
						_ressourcesManager.addToCachePriority(itemPage);
					}
					
					itemTemplate =  _ressourcesManager.getRessourceTemplate( _xmlContentPage.children()[0].@uiTemplate) as LoaderItemGroup;
					if (itemTemplate != null) {
						tabRessourceInitial.push(itemTemplate);
						_ressourcesManager.addToCachePriority(itemTemplate);
					}

					
				}else
				{
					uipage = getIdPageClean(_deepLinkToLoad);

					
					itemPage = _ressourcesManager.getRessourcePage(uipage) as LoaderItemGroup;
					if (itemPage != null)
					{
						tabRessourceInitial.push(itemPage);
						_ressourcesManager.addToCachePriority(itemPage);

						var nodePage:XML = _xmlTemplates.pages.children().(@uipage == itemPage.id)[0];
						itemTemplate = _ressourcesManager.getRessourceTemplate(nodePage.@uiTemplate) as LoaderItemGroup;
						if (itemTemplate != null) {
							tabRessourceInitial.push(itemTemplate);
							_ressourcesManager.addToCachePriority(itemTemplate);
						}
					}else {
						_deepLinkToLoad = "";
					}
					
				}
				
				
			}	
			
			

			

			// on lance le chargement
			_loaderManager.reset();
			_loaderManager.tabToLoad = tabRessourceInitial;
			_loaderManager.addEventListener(LoaderEvent.COMPLETED, onRessourcesLoaded);
			_loaderManager.addEventListener(LoaderEvent.PROGRESS, onRessourcesProgress);
			_loaderManager.start();
			
			//affichage de la progression du chargement
			_loaderPanel = _loaderPanelSite;
			_loaderPanel.container = this;
			_loaderPanel.display();	
			
		}
		

		//----------------------------------------------------------------------
		private function onRessourcesProgress(evt:LoaderEvent)
		{
			_loaderPanel.setProgress(evt.percent);
			
		}
		//----------------------------------------------------------------------
		private function onRessourcesLoaded(evt:LoaderEvent)
		{
			debugIt("-----------------------------------------------------");
			debugIt("ON RESSOURCES LOADED");
			debugIt("-----------------------------------------------------");
			_loaderManager.removeEventListener(LoaderEvent.COMPLETED, onRessourcesLoaded);
			_loaderManager.removeEventListener(LoaderEvent.PROGRESS, onRessourcesProgress);

			_idCurrentPage = _deepLinkToLoad;
			
			_loaderPanel.hide();
			
			
			_instance.dispatchEvent(new ContainerLoaderEvent(ContainerLoaderEvent.RESSOURCES_LOADED));
				
			
		}
	
		
		
		
		
		//----------------------------------------------------------------------
		//----------------------------------------------------------------------
		//----- Gestion chargement couple Page/ressource
		//----------------------------------------------------------------------
		//----------------------------------------------------------------------

		public function loadPage(id:String)
		{
			
			
			//if (_deepLinkFirst == null || ( _deepLinkFirst != null && _deepLinkFirst != id))
			//{
				debugIt("  ");
				debugIt("  ");
				debugIt(">>>>>  ");
				debugIt("loadPage " + id);
				debugIt("_deepLinkFirst " + _deepLinkFirst);
				debugIt(">>>>>  ");
				
				_deepLinkToLoad = id;
				
				if (id.indexOf(".xml") != -1 )
				{

					_instance.loadPageXml();
					
				}else
				{
					_instance._loadPage();
				}
			/*}else {
				
				debugIt("_deepLinkFirst " + _deepLinkFirst);
				
				_deepLinkFirst = null;
				
				// event
				var ev:ContainerLoaderEvent = new ContainerLoaderEvent(ContainerLoaderEvent.RESSOURCES_PAGE_LOADED);
				_instance.dispatchEvent(ev);
				
				
			}*/
			
		}
		private function _loadPage(evt:Event = null)
		{

			trace("_onLoadingPage " + _onLoadingPage);
			if (!_onLoadingPage)
			{
	
					var uipage:String = getIdPageClean(_deepLinkToLoad);
					trace("uipage " + uipage);
					
					
					var itemPage:LoaderItemGroup = _ressourcesManager.getRessourcePage(uipage) as LoaderItemGroup;
					var pageData:PageData = _dataManager.getPageData(uipage);
					var itemTemplate:LoaderItemGroup;
					

					if (_xmlTemplates.pages.children().(@uipage == uipage)[0] is XML && itemPage != null)
					{
						
						
						_loaderPanel = _loaderPanelPage;
						_loaderPanel.container = this;

						if (pageData.uiTemplate != null)
						{
							itemTemplate = _ressourcesManager.getRessourceTemplate(pageData.uiTemplate) as LoaderItemGroup;
						}
										

						if (itemTemplate != null && !itemTemplate.completed)
						{
							_onLoadingPage = true;
							_loaderPanel.display();
							_ressourcesManager.addEventListener(LoaderEvent.PRIORITY_COMPLETED, onPriorityLoadCompleted);
							_ressourcesManager.addEventListener(LoaderEvent.PRIORITY_PROGRESS, onPriorityLoadProgress);
							_ressourcesManager.loadInPriority(itemPage, itemTemplate);
						}else if (!itemPage.completed)
						{
							_onLoadingPage = true;
							_loaderPanel.display();
							_ressourcesManager.addEventListener(LoaderEvent.PRIORITY_COMPLETED, onPriorityLoadCompleted);
							_ressourcesManager.addEventListener(LoaderEvent.PRIORITY_PROGRESS, onPriorityLoadProgress);
							_ressourcesManager.loadInPriority(itemPage);

						}else {
							_idCurrentPage = _deepLinkToLoad;
							
							// event
							var ev:ContainerLoaderEvent = new ContainerLoaderEvent(ContainerLoaderEvent.RESSOURCES_PAGE_LOADED);
							ev.deepLink = _deepLinkToLoad;
							_instance.dispatchEvent(ev);
							
							_onLoadingPage = false;
							
						}
					}else {		
						debugIt("XXXXX  pas de page à charger pour le deepLink " + _deepLinkToLoad);
						_onLoadingPage = false;
						// event
						var ev4:ContainerLoaderEvent = new ContainerLoaderEvent(ContainerLoaderEvent.ERROR_LOAD);
						_instance.dispatchEvent(ev4);

					}
					
				
			}else{
			
					debugIt("XXXX LOAD not. Un Loading est déja en cours !");
					_onLoadingPage = false;
					// event
					var ev3:ContainerLoaderEvent = new ContainerLoaderEvent(ContainerLoaderEvent.ERROR_LOAD);
					_instance.dispatchEvent(ev3);
					
					
					
			}
			
		}


		private function onPriorityLoadCompleted(evt:LoaderEvent)
		{
			
			_ressourcesManager.removeEventListener(LoaderEvent.PRIORITY_COMPLETED, onPriorityLoadCompleted);
			_ressourcesManager.removeEventListener(LoaderEvent.PRIORITY_PROGRESS, onPriorityLoadProgress);
			
			debugIt("--> onPriorityLoadCompleted");
			_loaderPanel.hide();
			
			_idCurrentPage = _deepLinkToLoad;
			
			// event
			var ev:ContainerLoaderEvent = new ContainerLoaderEvent(ContainerLoaderEvent.RESSOURCES_PAGE_LOADED);
			ev.deepLink = _deepLinkToLoad;
			_instance.dispatchEvent(ev);
			
			_onLoadingPage = false;
			


			
		}
		private function onPriorityLoadProgress(evt:LoaderEvent)
		{
			_loaderPanel.setProgress( evt.percent);
		}	
		
		
		//----------------------------------------------------------------------
		//----------------------------------------------------------------------
		//----- loadRessource indépendante du systeme d'affichage de page
		//----------------------------------------------------------------------
		//----------------------------------------------------------------------
		public function loadGroupRessource(obj:Object):LoaderItemGroup
		{
			return _instance._loadGroupRessource(obj);

		}
		
		public function _loadGroupRessource(obj:Object):LoaderItemGroup
		{
			//_onLoadingPage = true;
			var item:LoaderItemGroup;
			
			if (obj is String) {
				
				item = getLoaderItemPage(obj as String);
				if (item == null) item = getLoaderItemTemplate(obj as String);
				if (item == null) item = getLoaderItemRessource(obj as String);
			}else if (obj is LoaderItemGroup) {
				item = obj as LoaderItemGroup;
			}
			
			
			
			if (item != null && !item.completed) {
				
				//_loaderPanel = _loaderPanelPage;
				//_loaderPanel.container = this;
				
				_ressourcesManager.addEventListener(LoaderEvent.PRIORITY_COMPLETED, onRessourceCompleted);
				//_ressourcesManager.addEventListener(LoaderEvent.PRIORITY_PROGRESS, onPriorityLoadProgress);
				//_loaderPanel.display();
				
				_ressourcesManager.loadInPriority(item);
				
				function onRessourceCompleted(evt:LoaderEvent)
				{
					//_loaderPanel.hide();
					_ressourcesManager.removeEventListener(LoaderEvent.PRIORITY_COMPLETED, onRessourceCompleted);
					//_ressourcesManager.removeEventListener(LoaderEvent.PRIORITY_PROGRESS, onPriorityLoadProgress);
				}
				
				return item;
				
			}else {
				//_onLoadingPage = false;
				return null;
			}
			
			
			
			
		}
		
		//----------------------------------------------------------------------
		//----------------------------------------------------------------------
		//----- Gestion loading in backgound et mise en cache
		//----------------------------------------------------------------------
		//----------------------------------------------------------------------
		//----------------------------------------------------------------------
		public function addInBackgroundLoading(id:String):void
		{
			var item:LoaderItemGroup = getLoaderItemPage(id);
			if (item == null) item = getLoaderItemTemplate(id);
			if (item == null) item = getLoaderItemRessource(id);
			
			
			if(item  != null) _ressourcesManager.addToLoadInBackground(item);
			
		}
		public function addToCacheStatic(id:String):void
		{
			var item:LoaderItemGroup = getLoaderItemPage(id);
			if (item == null) item = getLoaderItemTemplate(id);
			if (item == null) item = getLoaderItemRessource(id);
			
			if(item  != null) _ressourcesManager.addToCacheStatic(item);
			
		}
		
		public function startBackgoundLoading():void
		{
			debugIt("-------------------------");
			debugIt("-------------------------");
			debugIt("startLoadInBackground");
			debugIt("-------------------------");
			debugIt("-------------------------");
			
			_ressourcesManager.loadStaticRessources();
		}
		//----------------------------------------------------------------------
		private function onBackgroundCompleted(evt:LoaderEvent)
		{
			debugIt("--> onBackgroundCompleted");
			debugIt("---------------------------------------------------------------------------");
			_loaderManager.removeEventListener(LoaderEvent.COMPLETED, onBackgroundCompleted);
			
			// event
			var ev:ContainerLoaderEvent = new ContainerLoaderEvent(ContainerLoaderEvent.FULL_LOADED);
			_instance.dispatchEvent(ev);	
		}
		
		
		//----------------------------------------------------------------------
		// load de page defini dans un xml externe
		//----------------------------------------------------------------------
		private function loadPageXml()
		{
			_xmlContentPage = null;
			
			var urlClean:String = _deepLinkToLoad;
			if ( _deepLinkToLoad.substring(0, 1) == "/") {
				urlClean = _deepLinkToLoad.substr(1, _deepLinkToLoad.length);
			}
			
			
			/*var tab:Array = _deepLinkToLoad.split(_splitDeepLink);
			if (tab != null && tab.length > 1) idClean = tab[0];*/
			
			
			_loaderPanel = _loaderPanelPage;
			_loaderPanel.container = this;
			_loaderPanel.display();
			
			_loaderItemXmlContent = new LoaderItemObject("xmlContent", _repLoc + urlClean);
			_instance.addEventListener("__onXmlContentLoaded", _loadPageXml);
			
			
			_loaderManager.addEventListener(LoaderEvent.COMPLETED, onXmlContentCompleted);
			_loaderManager.loadInPriority(_loaderItemXmlContent);

		}
		private function _loadPageXml(evt:Event = null)
		{
			debugIt(" --> _loadPageXml");
			
			
			trace("_onLoadingPage " + _onLoadingPage);
			if (!_onLoadingPage)
			{
	
					
						var itemTemplate:LoaderItemGroup;
					
						
						
						_loaderPanel = _loaderPanelPage;
						_loaderPanel.container = this;

						
						if (_xmlContentPage.children()[0].@uiTemplate != null)
						{
							itemTemplate = _ressourcesManager.getRessourceTemplate( _xmlContentPage.children()[0].@uiTemplate) as LoaderItemGroup;
						}
										

						trace("itemTemplate " + itemTemplate);
						trace("itemTemplate.completed " + itemTemplate.completed);
						
						if (itemTemplate != null && !itemTemplate.completed)
						{
							_onLoadingPage = true;
							_loaderPanel.display();
							_ressourcesManager.addEventListener(LoaderEvent.PRIORITY_COMPLETED, onPriorityLoadCompleted);
							_ressourcesManager.addEventListener(LoaderEvent.PRIORITY_PROGRESS, onPriorityLoadProgress);
							_ressourcesManager.loadInPriority(itemTemplate);
						}else {
							_idCurrentPage = _deepLinkToLoad;
							
							// event
							var ev:ContainerLoaderEvent = new ContainerLoaderEvent(ContainerLoaderEvent.RESSOURCES_PAGE_LOADED);
							ev.deepLink = _deepLinkToLoad;
							_instance.dispatchEvent(ev);
							
							_onLoadingPage = false;
							
						}
					
				
			}else{
			
					debugIt("XXXX LOAD not. Un Loading est déja en cours !");
					// event
					var ev3:ContainerLoaderEvent = new ContainerLoaderEvent(ContainerLoaderEvent.ERROR_LOAD);
					_instance.dispatchEvent(ev3);
					
					_onLoadingPage = false;
					
			}
			
			
		}
		
		
		
		//----------------------------------------------------------------------
		// Debug
		//----------------------------------------------------------------------
		private function initDebug()
		{
			if ( String(_xmlConfig.debug.@value) == "true") {
				_debugMode = true;
			}
			
			
			
			if(_debugMode)
			{
				Debug.clear() 
				Debug.monitor(stage);
				
				
			}
			
		} 
		
		public function debugIt(str:Object, tmpNum:Number = 1)
		{
			
			
			if (Capabilities.playerType == "External")
			{
				trace(str);
			}else if(_debugMode)
			{
				Debug.trace(str, tmpNum);
				trace(str);
			}
			
			
		}	
		
		//----------------------------------------------------------------------
		// SWF ADDRESS
		//----------------------------------------------------------------------
		public function setSwfAdrress(chaine:String, title:String = "")
		{
			
			debugIt(" setSwfAdrress " + chaine);
			
			SWFAddress.removeEventListener(SWFAddressEvent.CHANGE, _instance.onSwfAdressChange);
			
			
			if (_isSwfAdd) {
				try{
					var nodeSWFAd:XMLList = _listAd.address.(@deepLink == chaine);
					
					var valPageAd:String 	= ""	;
					var valPageTitle:String = ""	;

					
					if ( nodeSWFAd.length() > 0) {
						valPageAd 		= 	nodeSWFAd.attribute('addressPage');
						valPageTitle 	=	nodeSWFAd.attribute('titlePage');
					}else {

							var c:String = "/" + _instance.getIdPageClean(chaine);
							nodeSWFAd = _listAd.address.(@deepLink == c);

							if ( nodeSWFAd.length() > 0) {
								valPageAd 		= 	nodeSWFAd.attribute('addressPage');
								valPageTitle 	=	nodeSWFAd.attribute('titlePage');

								var tab:Array = chaine.split(c);
								if (tab.length > 1) valPageAd += tab[1];
							
							}else {
								valPageAd = chaine;
								valPageTitle = title;
							}
					}
					
					SWFAddress.setValue(valPageAd);
					SWFAddress.setTitle(valPageTitle);
					
					debugIt("SwfAdress SET CHANGE " + valPageAd);

				

				}catch (e) {
					debugIt("SwfAdress NOT Exist " + chaine );
					SWFAddress.setValue(chaine);
					if(title != "") SWFAddress.setTitle(title);
				}
			}else {
				debugIt("SwfAdress NOT actif " + chaine );
				
				SWFAddress.setValue(chaine);
				if(title != "") SWFAddress.setTitle(title);
			}
			
			SWFAddress.addEventListener(SWFAddressEvent.CHANGE, _instance.onSwfAdressChange);
			
			
			
		}
		public function getSwfAdress():String
		{
			return SWFAddress.getValue();
		}
		public function setSwfAdrressTitle(title:String)
		{
			SWFAddress.setTitle(title);
		}
		public function getDeepLinkFromSwfAdd(chaine:String):String
		{
			var ret:String;
			
			try{
				var nodeSWFAd:XMLList = _listAd.address.(@addressPage == chaine);
				if ( nodeSWFAd.length() > 0) {
						ret = nodeSWFAd.attribute('deepLink');
				}else {

						var c:String = "/" + _instance.getIdPageClean(chaine);
						nodeSWFAd = _listAd.address.(@addressPage == c);

						if ( nodeSWFAd.length() > 0) {
							ret = nodeSWFAd.attribute('deepLink');

							var tab:Array = chaine.split(c);
							if (tab.length > 1) ret += tab[1];
						
						}else {
							ret = chaine;
						}
						

				}

			}catch (e) {
				ret = chaine;
			}
			
			return ret;
			
		}
		private function onSwfAdressChange(e:SWFAddressEvent)
		{
			
			var chaine:String = e.value;
			//debugIt("chaine " + chaine);
			//debugIt("_listAd " + _listAd);
			
			if(_isSwfAdd){
				if (_listAd != null) {

						var chaineF:String 		= getDeepLinkFromSwfAdd(chaine);
						debugIt("chaineF " + chaineF);
						
						if (chaineF) {
							// déclenchement event
							var evt:ContainerLoaderEvent = new ContainerLoaderEvent(ContainerLoaderEvent.SWFADRESS_CHANGE);
							evt.deepLink = chaineF;
							_instance.dispatchEvent(evt);
						}

					
				}
			}else {
				// déclenchement event en passant la chaine tel quelle
				var evt2:ContainerLoaderEvent = new ContainerLoaderEvent(ContainerLoaderEvent.SWFADRESS_CHANGE);
				evt2.deepLink = chaine;
				_instance.dispatchEvent(evt2);
			}
				
		}

	}
}